<?php
class apache_log_parser
{
        var $bad_rows; // Number of bad rows
        var $fp; // File pointer 

        function format_log_line($line) 
        { 
                preg_match("/(\d+\.\d+\.\d+\.\d+).*\[([^:]+):(\d+:\d+:\d+) ([^\]]+)\] \"(\S+) (.*?) (\S+)\" (\S+) (\S+)\s?(\".*?\")\s?(\".*?\")/", $line, $matches); // pattern to format the line 
                return $matches; 
        }

        function format_line($line) 
        { 
                $logs = $this->format_log_line($line); // format the line 
                if (isset($logs[0])) // check that it formated OK 
                { 
                        $formated_log             = array(); // make an array to store the lin info in 
                        $formated_log['ip']       = $logs[1]; 
                        // $formated_log['identity'] = $logs[2]; 
                        // $formated_log['user']     = $logs[2]; 
                        $formated_log['date']     = $logs[2]; 
                        $formated_log['time']     = $logs[3]; 
                        $formated_log['timezone'] = $logs[4]; 
                        $formated_log['method']   = $logs[5]; 
                        $formated_log['path']     = $logs[6]; 
                        $formated_log['protocal'] = $logs[7]; 
                        $formated_log['status']   = $logs[8]; 
                        $formated_log['bytes']    = $logs[9]; 
                        $formated_log['referer']  = empty($logs[10])?'':$logs[10]; 
                        $formated_log['agent']    = empty($logs[11])?'':$logs[11]; 
                        return $formated_log; // return the array of info 
                } 
                else 
                { 
                        $this->badRows++; // if the row is not in the right format add it to the bad rows 
                        return false; 
                } 
        } 

        function open_log_file($file_name) 
        { 
                $this->fp = fopen($file_name, 'r'); // open the file 
                if (!$this->fp) 
                { 
                        return false; // return false on fail 
                } 
                return true; // return true on sucsess 
        } 

        function close_log_file() 
        { 
                return fclose($this->fp); // close the file 
        } 

        // gets a line from the log file 
        function get_line() 
        { 
                if (feof($this->fp)) 
                { 
                        return false; 
                } 
                $bit  ='';
                $bits =''; 
                // I find for loops much much faster 
                for (;!feof($this->fp) && $bit != "\n";) 
                { 
                            $bit = fread($this->fp, 1);
                            $bits .= $bit;//fread($this->fp, 1); 
                } 
                return rtrim($bits, "\n"); 
        }

}
?>